import { ref } from 'vue'
import { supabase } from '../../lib/supabase'
import type { MovieUploadForm, MovieEditForm } from './types'
import { useMovieTagOperations } from '../tags'

export const useMovieOperations = () => {
  const { setMovieSystemTags } = useMovieTagOperations()
  
  // 操作状态
  const isUploading = ref(false)
  const isUpdating = ref(false)
  const isDeleting = ref(false)
  const uploadError = ref<string | null>(null)
  const updateError = ref<string | null>(null)
  const deleteError = ref<string | null>(null)

  // 上传电影
  const uploadMovie = async (form: MovieUploadForm, coverFile?: File): Promise<number> => {
    try {
      isUploading.value = true
      uploadError.value = null

      // 上传封面图片
      let coverUrl = ''
      if (coverFile) {
        const fileName = `covers/${Date.now()}_${coverFile.name}`
        const { data: uploadData, error: uploadError } = await supabase.storage
          .from('movies')
          .upload(fileName, coverFile)

        if (uploadError) {
          throw new Error(`上传封面失败: ${uploadError.message}`)
        }

        const { data: urlData } = supabase.storage
          .from('movies')
          .getPublicUrl(fileName)

        coverUrl = urlData.publicUrl
      }

      // 创建电影记录 - 只插入movies表中存在的字段
      const { data, error } = await supabase
        .from('movies')
        .insert({
          title: form.title,
          original_title: form.originalTitle,
          year: form.year,
          duration: form.duration,
          director: form.directors.join(', '),
          rating: form.rating,
          tags: form.tags, // 用户自定义标签
          actors: form.actors,
          description: form.description,
          plot: form.plot,
          budget: form.budget,
          box_office: form.box_office,
          awards: form.awards,
          trivia: form.trivia,
          is_ai: form.isAi,
          cover_url: coverUrl,
          uploader_id: (await supabase.auth.getUser()).data.user?.id
        })
        .select('id')
        .single()

      if (error) {
        throw new Error(`创建电影失败: ${error.message}`)
      }

      // 使用数据库函数设置系统标签
      if (data.id) {
        console.log('设置电影系统标签:', {
          movieId: data.id,
          genres: form.genres,
          universe: form.universe,
          language: form.language,
          country: form.country
        })

        const { data: tagResult, error: tagError } = await supabase
          .rpc('set_movie_system_tags_simple', {
            p_movie_id: data.id,
            p_genre_names: form.genres.length > 0 ? form.genres : null,
            p_universe_name: form.universe || null,
            p_language_name: form.language || null,
            p_country_name: form.country || null
          })

        if (tagError) {
          console.error('设置系统标签失败:', tagError)
          // 不抛出错误，因为电影已经创建成功
        } else {
          console.log('系统标签设置结果:', tagResult)
        }
      }

      return data.id
    } catch (err) {
      uploadError.value = err instanceof Error ? err.message : '上传失败'
      console.error('上传电影失败:', err)
      throw err
    } finally {
      isUploading.value = false
    }
  }

  // 更新电影
  const updateMovie = async (movieId: number, form: MovieEditForm, coverFile?: File): Promise<void> => {
    try {
      isUpdating.value = true
      updateError.value = null

      // 上传新的封面图片
      let coverUrl = ''
      if (coverFile) {
        const fileName = `covers/${Date.now()}_${coverFile.name}`
        const { data: uploadData, error: uploadError } = await supabase.storage
          .from('movies')
          .upload(fileName, coverFile)

        if (uploadError) {
          throw new Error(`上传封面失败: ${uploadError.message}`)
        }

        const { data: urlData } = supabase.storage
          .from('movies')
          .getPublicUrl(fileName)

        coverUrl = urlData.publicUrl
      }

      // 更新电影记录 - 只更新movies表中存在的字段
      const updateData: any = {
        title: form.title,
        original_title: form.originalTitle,
        year: form.year,
        duration: form.duration,
        director: form.directors.join(', '),
        rating: form.rating,
        tags: form.tags, // 用户自定义标签
        actors: form.actors,
        description: form.description,
        plot: form.plot,
        budget: form.budget,
        box_office: form.box_office,
        awards: form.awards,
        trivia: form.trivia,
        is_ai: form.isAi
      }

      if (coverUrl) {
        updateData.cover_url = coverUrl
      }

      const { error } = await supabase
        .from('movies')
        .update(updateData)
        .eq('id', movieId)

      if (error) {
        throw new Error(`更新电影失败: ${error.message}`)
      }

      // 使用数据库函数更新系统标签
      console.log('更新电影系统标签:', {
        movieId,
        genres: form.genres,
        universe: form.universe,
        language: form.language,
        country: form.country
      })

      const { data: tagResult, error: tagError } = await supabase
        .rpc('set_movie_system_tags_simple', {
          p_movie_id: movieId,
          p_genre_names: form.genres.length > 0 ? form.genres : null,
          p_universe_name: form.universe || null,
          p_language_name: form.language || null,
          p_country_name: form.country || null
        })

      if (tagError) {
        console.error('更新系统标签失败:', tagError)
        // 不抛出错误，因为电影已经更新成功
      } else {
        console.log('系统标签更新结果:', tagResult)
      }
    } catch (err) {
      updateError.value = err instanceof Error ? err.message : '更新失败'
      console.error('更新电影失败:', err)
      throw err
    } finally {
      isUpdating.value = false
    }
  }

  // 删除电影
  const deleteMovie = async (movieId: number): Promise<void> => {
    try {
      isDeleting.value = true
      deleteError.value = null

      // 删除电影记录
      const { error } = await supabase
        .from('movies')
        .delete()
        .eq('id', movieId)

      if (error) {
        throw new Error(`删除电影失败: ${error.message}`)
      }
    } catch (err) {
      deleteError.value = err instanceof Error ? err.message : '删除失败'
      console.error('删除电影失败:', err)
      throw err
    } finally {
      isDeleting.value = false
    }
  }

  // 增加观看次数
  const incrementViews = async (movieId: number): Promise<void> => {
    try {
      const { error } = await supabase
        .rpc('increment_movie_views', { p_movie_id: movieId })

      if (error) {
        console.error('增加观看次数失败:', error)
      }
    } catch (err) {
      console.error('增加观看次数失败:', err)
    }
  }

  // 点赞/取消点赞
  const toggleLike = async (movieId: number): Promise<void> => {
    try {
      const { error } = await supabase
        .rpc('toggle_movie_like', { p_movie_id: movieId })

      if (error) {
        console.error('切换点赞状态失败:', error)
      }
    } catch (err) {
      console.error('切换点赞状态失败:', err)
    }
  }

  // 获取电影统计信息
  const getMovieStats = async (movieId: number) => {
    try {
      const { data, error } = await supabase
        .rpc('get_movie_stats', { p_movie_id: movieId })

      if (error) {
        console.error('获取电影统计失败:', error)
        return null
      }

      return data
    } catch (err) {
      console.error('获取电影统计失败:', err)
      return null
    }
  }

  return {
    // 状态
    isUploading,
    isUpdating,
    isDeleting,
    uploadError,
    updateError,
    deleteError,
    
    // 方法
    uploadMovie,
    updateMovie,
    deleteMovie,
    incrementViews,
    toggleLike,
    getMovieStats
  }
}
